package yxy.apple.http.cookie;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.http.client.CookieStore;

import yxy.apple.util.FileUtility;

public class FileCookieStorage implements CookieStorage {

	private File file = null;

	public FileCookieStorage(File file) {
		this.file = file;
	}

	@Override
	public void save(CookieStore cs) throws IOException {
		ObjectOutputStream stream = null;
		try {
			FileUtility.create(this.file);
			stream = new ObjectOutputStream(new FileOutputStream(this.file));
			stream.writeObject(cs);
			stream.flush();
			stream.close();
		} catch (Exception e) {
			if (stream != null) {
				stream.flush();
				stream.close();
			}
			throw new IOException(e);
		}

	}

	@Override
	public CookieStore load() throws IOException {
		ObjectInputStream stream = null;
		try {
			if (this.file.exists() && this.file.isFile() && this.file.canRead()) {
				stream = new ObjectInputStream(new FileInputStream(this.file));
				CookieStore cs = (CookieStore) stream.readObject();
				stream.close();
				return cs;
			} else {
				return null;
			}
		} catch (Exception e) {
			if (stream != null) {
				stream.close();
			}
			throw new IOException(e);
		}
	}

}
